package cn.lml.lession.user.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.lml.lession.user.model.Module;
import cn.lml.lession.user.model.Role;
import cn.lml.lession.user.service.ModuleService;

@RestController
@RequestMapping("/module")
public class ModuleController {

	private static final Logger logger = LoggerFactory.getLogger(ModuleController.class);
	@Autowired
	private ModuleService moduleService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> save(Module module) {
		logger.info("保存数据 " + module);
		Integer mid = module.getMid();
		if (mid == null) {
			module.setMid((int)(99999000+Math.round(Math.random()*1000)+Math.round(Math.random()*100)+Math.round(Math.random()*10)));
			moduleService.insertModule(module);
		} else {
			moduleService.updateByMid(module);
		}
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("state", 1);
		responseMap.put("msg", "保存成功");
		return responseMap;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Map<String, Object> delete(@RequestParam(value = "mid") Integer mid) {
		logger.info("删除数据 " + mid);
		moduleService.deleteByMid(mid);
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("state", 1);
		responseMap.put("msg", "删除成功");
		return responseMap;
	}

	@RequestMapping(value = "/select")
	public Module select(@RequestParam(value = "mid") Integer mid) {
		logger.info("查询数据 " + mid);
		return moduleService.selectByMid(mid);
	}

	@RequestMapping(value = "/query")
	public Map<String,Object> query(@RequestParam(value = "page", defaultValue = "1") Integer page,@RequestParam(value = "size", defaultValue = "10") Integer size) {
		logger.info("分页查询数据 page=" + page + " size=" + size);
		Map<String, Object> cond = new HashMap<String, Object>();
		cond.put("start", (page - 1) * size);
		cond.put("end", page * size);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("count",moduleService.countModule(cond));
		resultMap.put("dataList",moduleService.queryModule(cond));
		return resultMap;
	}
	
	@GetMapping(value = "/queryModuleByRoleId")
	public List<Module>  queryModuleByRoleId(@RequestParam(value = "rid") Integer rid) {
		logger.info("根据角色ID查询权限,rid={} ",rid);
		return moduleService.queryModuleByRoleId(rid);
	}
}

